<template>
	<view>
		<cu-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">{{friendName}}</block>
		</cu-custom>

		<view class="cu-chat">
			<view class="cu-info round">{{title}}</view>
			<view v-for="(item, key) in list" :key="key">
				<view v-if="item.mine" class="cu-item self">
					<view class="main">
						<view class="content bg-green shadow">
							<text v-if="item.mesType==0">{{item.mes}}</text>
							<image v-if="item.mesType==1 || item.mesType==2" :src="item.mes" :class="item.mesType==1?'face-image':'origin-image'"></image>
							<text v-if="item.off">【离线消息】</text>
						</view>
					</view>
					<view class="cu-avatar radius" :style="[{backgroundImage:'url('+ item.avatar +')'}]"></view>
					<view class="date">{{item.createTime}}</view>
				</view>

				<view v-else class="cu-item">
					<view class="cu-avatar radius" :style="[{backgroundImage:'url('+ item.avatar +')'}]"></view>
					<view class="main">
						<view class="content shadow">
							<text v-if="item.mesType==0">{{item.mes}}</text>
							<image v-if="item.mesType==1 || item.mesType==1" :src="item.mes" :class="item.mesType==1?'face-image':'origin-image'"></image>
							<text v-if="item.off">【离线消息】</text>
						</view>
					</view>
					<view class="date ">{{item.createTime}}</view>
				</view>
			</view>

		</view>


		<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
			<!-- 			<view class="action">
				<view class="cuIcon-sound text-gray"></view>
			</view> -->

			<input class="solid-bottom round" style="background-color: #f5f5f5;" :adjust-position="false" :focus="false"
			 maxlength="300" cursor-spacing="10" @focus="InputFocus" @blur="InputBlur" v-model="value"></input>

			<view class="action">
				<view @tap="showModel">
					<text class="cuIcon-emojifill text-grey"></text>
				</view>
				<view @tap="showToolModel">
					<text class="cuIcon-roundaddfill  text-grey"></text>
				</view>
			</view>

			<button class="cu-btn bg-green shadow" @tap="clickRequest">发送</button>
		</view>
		<view class="cu-modal bottom-modal" :class="hideCu?'show':''" @tap="hideModal">
			<view class="cu-dialog" @tap.stop>
				<view class="grid" style="margin-top: 4px ;margin-left: 6px;">
					<view class="cu-item-face" v-for="(item,key) in faceList" :key="key">
						<image :src="item" class="face-image" @tap="clickFace(key)"></image>
					</view>
				</view>
			</view>
		</view>

		<view class="cu-modal bottom-modal" :class="toolClass" @tap="hideToolModal">
			<view class="cu-dialog" @tap.stop>
				<view class="cu-list grid col-3">
					<view class="cu-item" @tap="clickChooseImg">
						<view class="cuIcon-picfill text-yellow"></view>
						<text><span>图片</span></text>
					</view>
					<view class="cu-item">
						<view class="cuIcon-recordfill  text-orange"></view>
						<text><span>视频</span></text>
					</view>
					<view class="cu-item">
						<view class="cuIcon-file text-grey"></view>
						<text><span>文件</span></text>
					</view>
				</view>
			</view>
		</view>


		<view class="cu-load load-modal" v-if="loadModal">
			<!-- <view class="cuIcon-emojifill text-orange"></view> -->
			<view class="gray-text">发送中...</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loadModal: false,
				title: '下拉查看更多记录',
				pageNo: -1,
				hideTool: false,
				hideCu: false,
				InputBottom: 0,
				value: '',
				tableData: [],
				list: this.$soket.chatMessage,
				start: true,
				globalUserId: this.$soket.globalUserId,
				friendName: '聊天',
				// faceList: ["/static/face/f0.gif", "/static/face/f1.gif"],
				// originFace: ["[f0]", "[f1]"],
				faceList: this.$soket.faceList,
				originFace: this.$soket.originFace,
				limitFlag: true
			};
		},
		methods: {
			hideToolModal(e) {
				this.hideTool = false;
			},
			showToolModel(e) {
				this.hideTool = true;
			},
			hideModal(e) {
				this.hideCu = false;
			},
			showModel(e) {
				this.hideCu = true;
			},
			InputFocus(e) {
				this.InputBottom = e.detail.height
			},
			InputBlur(e) {
				this.InputBottom = 0
			},
			clickRequest() {
				var con = this.value;
				if (con == '') {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '不能发送空白消息'
					});
				} else {
					//@TODO 校验商家发送限制

					this.commonSendMes(con);
				}
			},
			clickFace(index) {
				this.hideCu = false;
				this.value = 'face' + this.originFace[index];
			},
			clickChooseImg() {
				var that = this;

				//@TODO 校验商家发送限制

				uni.chooseImage({
					success: (chooseImageRes) => {
						var tempFilePaths = chooseImageRes.tempFilePaths;
						for (var i = 0; i < tempFilePaths.length; i++) {
							var filePath = tempFilePaths[i];
							uni.uploadFile({
								url: 'http://192.168.0.110/lxy/resource/core/upload',
								// url: '/lxy/resource/core/upload',
								filePath: filePath,
								name: 'file',
								formData: {
									'appId': 'a41ba4750257432aa3e099ef147e07e1'
								},
								success: (uploadFileRes) => {
									var data = JSON.parse(uploadFileRes.data);

									if (data.status) {
										//处理数据
										var downloadUrl = data.data.downloadUrl;
										var con = 'img[' + downloadUrl + ']';
										that.commonSendMes(con);
										this.hideTool = false;
									}
								},
								fail: (res) => {
									console.log(res);
								}
							});
						}
					},
					fail: (e) => {
						console.log(e);
					}
				});
			},
			commonSendMes(con) {
				var _self = this;
				_self.loadModal = true;
				var friendId = uni.getStorageSync('friendId');
				var friendUser = _self.$soket.getOnlineUserById(friendId);
				var ownLimitFlag = true;
				//@TODO 校验商家发送限制

				//查询限制否
				uni.request({
					method: 'POST',
					url: "http://192.168.0.110/im/api/record",
					// url: "/im/api/limit/admin",
					sslVerify: false,
					data: {
						"currentId": _self.globalUserId,
						'applicationKey': friendUser.applicationKey,
						'productUuid': friendUser.productUuid
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
					},
					success: (res) => {
						console.log("confirm limit", res)
						if (res.statusCode === 200) {
							ownLimitFlag = res.data.data.limitFlag;
						} else {
							uni.showToast({
								icon: 'none',
								position: 'bottom',
								title: res.data.message
							});
						}
					},
					complete: () => {
						if (_self.limitFlag || ownLimitFlag) {
							_self.loadModal = false;
							uni.showToast({
								icon: 'none',
								position: 'bottom',
								title: '已超过发送限制，去支付或者联系管理员'
							});
							return;
						}

						var ownUser = _self.$soket.getOnlineUserById(_self.globalUserId);
						var content = {
							from: ownUser.userId,
							to: friendUser.userId,
							cmd: 11,
							createTime: _self.$soket.happenTimeFun(new Date().getTime()),
							chatType: '2',
							msgType: '0',
							fromAvatar: ownUser.avatar,
							toAvatar: friendUser.avatar,
							applicationKey: friendUser.applicationKey,
							applicationName: friendUser.applicationName,
							productUuid: friendUser.productUuid,
							productName: friendUser.productName,
							content: con
						};
						var ok = JSON.stringify(content);
						_self.$soket.websokect.send({
							data: ok,
							success: () => {
								ownUser.mine = true;
								var c = content.content;
								var mesType = _self.$soket.getContentType(c);
								ownUser.mesType = mesType;
								c = _self.$soket.replaceLayHtml(c);
								ownUser.mes = c;
								ownUser.createTime = content.createTime;
								var jsonStr = JSON.stringify(ownUser);
								_self.list.push(JSON.parse(jsonStr));
								_self.value = '';
							},
							fail: () => {
								uni.showToast({
									icon: 'none',
									position: 'bottom',
									title: '数据发送失败'
								});
							},
							complete: () => {
								_self.loadModal = false;
							}
						});
					}
				});
			},
		},
		onLoad() {
			this.friendName = uni.getStorageSync('friendName');
			this.limitFlag = this.$soket.limitFlag;
		},
		computed: {
			toolClass() {
				return this.hideTool ? 'show' : '';
			}
		},
		onPullDownRefresh() {
			var that = this;
			console.log('refresh');
			if (that.start) {
				uni.request({
					method: 'POST',
					url: "http://192.168.0.110/im/api/record",
					// url: "/im/api/record",
					sslVerify: false,
					data: {
						"currUserId": that.globalUserId,
						'id': uni.getStorageSync('friendId'),
						'pageNo': that.pageNo,
						'pageSize': 6
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
					},
					success: (res) => {
						console.log("record page-------", res)
						if (res.statusCode === 200) {
							that.pageNo = res.data.pageNo - 1;
							if (that.pageNo <= 0) {
								that.start = false;
								that.title = '已经到底啦';
							}
							var friends = res.data.friends;
							var arr = [];
							for (var key in friends) {
								var chatDatas = friends[key];
								for (var index in chatDatas) {
									var content1 = chatDatas[index].content;
									var user_id = chatDatas[index].from;
									var userInfo = that.$soket.getOnlineUserById(user_id);
									if (user_id === that.globalUserId) {
										userInfo.mine = true;
									} else {
										userInfo.mine = false;
									}

									userInfo.off = false;

									var mesType = that.$soket.getContentType(content1);
									userInfo.mesType = mesType;
									content1 = that.$soket.replaceLayHtml(content1);

									that.$set(userInfo, 'mes', content1)
									userInfo.createTime = that.$soket.happenTimeFun(chatDatas[index].createTime);
									var jsonStr = JSON.stringify(userInfo);
									arr.push(JSON.parse(jsonStr));
								}
							}

							if (arr.length > 0) {
								arr.reverse();
								arr.forEach((item) => {
									that.list.unshift(item);
								})
							}
						} else {
							uni.showToast({
								icon: 'none',
								position: 'bottom',
								title: res.data.message
							});
						}
					}
				});
			}
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
	}
</script>

<style>
	page {
		padding-bottom: 100upx;
	}

	.cu-item-face {
		padding: 5px 2px;
	}

	.face-image {
		width: 22px;
		height: 22px;
	}

	.origin-image {
		width: 100px;
		height: 100px;
	}

	.cu-bar .foot {}
</style>
